package per.jdz.demo;

import lombok.extern.slf4j.Slf4j;
import per.jdz.demo.domain.entity.PumpRecord;
import per.jdz.demo.service.PumpRecordService;

import java.io.*;
import java.math.BigDecimal;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Slf4j
public class ModbusTCPClient {

    private static final String SERVER_ADDRESS = "0.0.0.0"; // Modbus TCP 从站地址
    private static final int PORT = 502; // Modbus TCP 默认端口
    private static final int BUFFER_SIZE = 1024;

    public static void connectAndProcessData(PumpRecordService pumpRecordService) {
        try (Socket socket = new Socket(SERVER_ADDRESS, PORT)) {
            log.info("连接到 Modbus TCP 从站...");

            try (InputStream inputStream = socket.getInputStream()) {
                byte[] buffer = new byte[BUFFER_SIZE];

                while (true) {
                    int bytesRead = inputStream.read(buffer);

                    if (bytesRead > 0) {
                        PumpRecord res = parseModbusTCPPacket(buffer, bytesRead);
                        if (res != null) {
                            pumpRecordService.save(res);
                        }
                    } else {
                        log.warn("没有接收到数据");
                        break;
                    }
                    // 这里可以添加一个短暂的延迟，防止CPU占用过高
                    TimeUnit.SECONDS.sleep(1); // 休眠1秒
                }
            } catch (InterruptedException e) {
                log.error("线程被中断: {}", e.getMessage(), e);
            }
        } catch (IOException e) {
            log.error("连接或读取数据时发生错误: {}", e.getMessage(), e);
        }
    }

    private static PumpRecord parseModbusTCPPacket(byte[] data, int length) {
        ByteBuffer buffer = ByteBuffer.wrap(data, 0, length);

        // 读取事务标识符
        int transactionId = buffer.getShort();
        // 读取协议标识符
        int protocolId = buffer.getShort();
        // 读取长度
        int lengthField = buffer.getShort();
        // 读取单元标识符
        int unitId = buffer.get();
        // 读取功能码
        int functionCode = buffer.get();

        log.info("事务标识符: {}", transactionId);
        log.info("协议标识符: {}", protocolId);
        log.info("长度: {}", lengthField);
        log.info("单元标识符: {}", unitId);
        log.info("功能码: {}", functionCode);

        // 读取字节数
        int byteCount = buffer.get();
        log.info("字节数: {}", byteCount);

        try {
            PumpRecord pumpRecord = new PumpRecord();
            pumpRecord.setPpuab(BigDecimal.valueOf(buffer.getShort()));
            pumpRecord.setPpubc(BigDecimal.valueOf(buffer.getShort()));
            pumpRecord.setPpuca(BigDecimal.valueOf(buffer.getShort()));
            pumpRecord.setPpia(BigDecimal.valueOf(buffer.getShort()));
            pumpRecord.setPpib(BigDecimal.valueOf(buffer.getShort()));
            pumpRecord.setPpic(BigDecimal.valueOf(buffer.getShort()));
            pumpRecord.setPpapwr(BigDecimal.valueOf(buffer.getShort()));
            pumpRecord.setPprpwr(BigDecimal.valueOf(buffer.getShort()));
            log.info("{}", buffer.getShort());
            pumpRecord.setPpcos(BigDecimal.valueOf(buffer.getShort()));
            pumpRecord.setClltm(new Date());
            pumpRecord.setPrjnmcd(String.valueOf(transactionId));
            System.out.println(pumpRecord);
            // 检查是否有剩余未读数据
            if (buffer.remaining() > 0) {
                log.warn("缓冲区中仍有 {} 字节未读取", buffer.remaining());
            }
            return pumpRecord;
        } catch (Exception e) {
            log.error("数据解析发生错误: {}", e.getMessage(), e);
        }
        return null;
    }
}